import React, { useState } from "react";
import {
  Switch,
  Spin,
  Tag,
  Space,
  Breadcrumb,
  Table,
  message,
  Popconfirm,
  Drawer,
  Row,
  Col,
  Avatar,
  Badge,
  Modal,
  Select,
  Input
} from "antd";
import {
  AudioOutlined,
  MailOutlined,
  GithubFilled,
  DeploymentUnitOutlined,
  SmileOutlined,
  ClusterOutlined,
  EyeFilled,
  EditFilled,
  ManOutlined,
  WomanOutlined,
  DeleteFilled,
  PlusCircleOutlined,
  ExclamationCircleOutlined,
  ContactsOutlined,
} from "@ant-design/icons";
import "./student.css";
import { Link } from "react-router-dom";
import {
  _getStuList,
  _updateStuCode,
  _updateAdmin,
  _delStu,
  _getCodeList,
} from "../../util/api/user/index";
const { confirm } = Modal;
const { Option } = Select;
const url = require("../../util/conUrl");

class NewsList extends React.Component {
  state = {
    isLoading: false,
    userList: null,
    visible: false,
    userItem: {},
    e_visible: false,
    confirmLoading: false,

    codeList: [],
    user_id: null,
    user_work: "",
    user_code_id: null,
    user_grade:""
  };
  getData = () => {
    this.setState({ isLoading: true });
    _getStuList()
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          console.log(res.data.data);
          this.setState({ isLoading: false });

          const userList = res.data.data;
          for (let i = 0; i < userList.length; i++) {
            userList[i].email = userList[i].user_email;
            userList[i].userName = userList[i].user_name;
            userList[i].git = userList[i].user_git;
            userList[i].userType = userList[i].user_type;
            userList[i].useStudyDir = userList[i].user_study_dir;
            userList[i].codeName = userList[i].user_code_name;
            userList[i].userWork = userList[i].user_work;
            userList[i].isAdmin = userList[i].isadmin;
            userList[i].control = userList[i].user_id;
          }
          this.setState({ userList: userList });
        }
      })
      .catch((e) => {
        this.setState({ isLoading: false });
        console.log(e);
        message.error("服务器错误");
      });
  };
  componentDidMount = () => {
    this.getData();
  };

  deletSource = (val) => {
    console.log(val);
    _delStu(val)
      .then((res) => {
        console.log(res);
        if (res.status === 200 && res.data.code === 0) {
          if (res.data.data && res.data.data.code === -1) {
            message.warning(res.data.data.msg);
          } else {
            message.success("删除成功");
            this.getData();
          }
        } else if (res.status === 200 && res.data.code === -1) {
          message.info(res.data.msg);
        }
      })
      .catch(() => {
        this.setState({ isLoading: false });
        message.error("服务器错误");
      });
  };

  handleAdmin = (val, user_id) => {
    let self = this;
    let temp = {};
    // console.log(val);
    if (val) {
      confirm({
        title: "你确定要执行此操作吗？",
        icon: <ExclamationCircleOutlined />,
        content: "取消授权后该用户将失去管理权限",
        onOk() {
          temp.isadmin = 0;
          _updateAdmin(user_id, temp).then((res) => {
            if (res.status === 200 && res.data.code === 0) {
              message.success("取消授权成功");
              self.getData();
            } else if (res.status === 200 && res.data.code === -1) {
              message.info(res.data.msg);
            }
            // console.log(res);
          });
        },
        onCancel() {},
      });
      //授权
    } else {
      confirm({
        title: "你确定要执行此操作吗？",
        icon: <ExclamationCircleOutlined />,
        content: "授权后该用户将获得管理权限",
        onOk() {
          temp.isadmin = 1;
          _updateAdmin(user_id, temp).then((res) => {
            if (res.status === 200 && res.data.code === 0) {
              message.success("授权成功");
              self.getData();
            } else if (res.status === 200 && res.data.code === -1) {
              message.info(res.data.msg);
            }
            // console.log(res);
          });
        },
        onCancel() {},
      });
    }
  };
  viewHandle = (val) => {
    // console.log(val);
    this.setState({
      visible: true,
      userItem: val,
    });
  };

  handleCancel = (e) => {
    this.setState({
      visible: false,
      e_visible: false,
    });
  };
  onInputChange = (e) => {
    this.setState({ user_work: e.target.value });
  };
  codeChange = (e) => {
    this.setState({ user_code_id: e });
  };
  gradeChange = (e) => {
    this.setState({user_grade:e})
  }
  showStuCodeMdal = (val) => {
    this.setState({
      e_visible: true,
      user_id: val,
    });
    _getCodeList().then((res) => {
      this.setState({ codeList: res.data.data });
    });
  };
  handleChangeStuCode = () => {
    if (!this.state.user_code_id || !this.state.user_grade) {
      message.warning("请填写信息");
      return false;
    }
    this.setState({
      confirmLoading: true,
    });
    let tempData = {
      user_code_id: this.state.user_code_id,
      user_work: this.state.user_work,
      user_grade :this.state.user_grade
    };
    console.log(tempData);
    _updateStuCode(this.state.user_id, tempData)
      .then((res) => {
        if (res.status === 200) {
          this.setState({
            e_visible: false,
            confirmLoading: false,
          });
          message.success("修改成功");
          this.getData();
        }
      })
      .catch(() => {
        this.setState({ confirmLoading: false, e_visible: false });
        message.error("服务器错误");
      });
  };

  render() {
    let userItem = this.state.userItem;
    let userGrade = "";
    if (userItem.user_grade >= 4) {
      userGrade = "博士";
    } else {
      userGrade = `研${userItem.user_grade}`;
    }
    const columns = [
      {
        title: "姓名",
        dataIndex: "userName",
      },
      {
        title: "邮箱",
        dataIndex: "email",
      },
      {
        title: "Git",
        dataIndex: "git",
      },
      {
        title: "学/专硕",
        dataIndex: "userType",
      },
      {
        title: "主研究方向",
        dataIndex: "useStudyDir",
      },
      {
        title: "状态",
        dataIndex: "codeName",
        render: (text, record) => (
          <Tag color="blue" key={text}>
            {text}
          </Tag>
        ),
      },
      {
        title: "公司",
        dataIndex: "userWork",
        render: (text, record) => <>{text == "" ? "无" : text}</>,
      },
      {
        title: "授权",
        dataIndex: "isAdmin",
        render: (text, record) => (
          <>
            <Switch
              checkedChildren="取消"
              unCheckedChildren="授权"
              // defaultChecked={text}
              checked={text}
              onClick={this.handleAdmin.bind(this, text, record.user_id)}
            />
          </>
        ),
      },
      {
        title: "操作",
        dataIndex: "control",
        render: (text, record) => (
          <Space size="middle">
            <EyeFilled onClick={this.viewHandle.bind(this, record)} />
            <Drawer
              placement="left"
              closable={false}
              onClose={this.handleCancel}
              visible={this.state.visible}
              width="30vw"
            >
              <Row justify="center">
                <Col span={20} className="stu-container">
                  {userItem.user_type === "专" ? (
                    <Badge
                      count={userItem.user_type}
                      style={{ backgroundColor: "#74b9ff" }}
                    >
                      <Avatar
                        size={100}
                        src={url.api + "/file/avatar/" + userItem.user_img}
                      />
                    </Badge>
                  ) : (
                    <Badge count={userItem.user_type}>
                      <Avatar
                        size={100}
                        src={url.api + "/file/avatar/" + userItem.user_img}
                      />
                    </Badge>
                  )}

                  <br />
                  <h3>{userItem.user_name}</h3>
                  <h4>
                    {userItem.user_gender === 0 ? (
                      <WomanOutlined style={{ color: "#ff7675" }} />
                    ) : (
                      <ManOutlined style={{ color: "#0984e3" }} />
                    )}
                  </h4>

                  <div className="stu-item">
                    <Space>
                      <MailOutlined /> {userItem.email}
                    </Space>
                  </div>
                  <div className="stu-item">
                    <Space>
                      <GithubFilled /> {userItem.git}
                    </Space>
                  </div>
                  <div className="stu-item">
                    <Space>
                      <DeploymentUnitOutlined />
                      <Tag color="magenta">{userItem.user_study_dir}</Tag>
                    </Space>
                  </div>
                  <div className="stu-item">
                    <Space>
                      <SmileOutlined />
                      <Tag color="blue">{userItem.user_code_name}</Tag>
                    </Space>
                  </div>
                  <div className="stu-item">
                    <Space>
                      <ContactsOutlined />
                      {userItem.user_work === "" ? "无" : userItem.user_work}
                    </Space>
                  </div>
                  <div className="stu-item">
                    <Space>
                      <ClusterOutlined />
                      <Tag color="purple">{userGrade}</Tag>
                    </Space>
                  </div>
                </Col>
              </Row>
            </Drawer>
            <ContactsOutlined onClick={this.showStuCodeMdal.bind(this, text)} />
            <Modal
              title="修改状态"
              visible={this.state.e_visible}
              onOk={this.handleChangeStuCode}
              confirmLoading={this.state.confirmLoading}
              onCancel={this.handleCancel}
              width={360}
            >
              <Space direction="vertical" size="large">
                <Select
                  placeholder="年级"
                  style={{ width: "100%" }}
                  allowClear
                  placeholder="年级"
                  onChange={this.gradeChange}
                >
                  <Option value={4}>博士</Option>
                  <Option value={3}>研三</Option>
                  <Option value={2}>研二</Option>
                  <Option value={1}>研一</Option>
                </Select>
                <Select
                  placeholder="学生状态"
                  onChange={this.codeChange}
                  allowClear
                  style={{ width: "100%" }}
                >
                  {this.state.codeList.map((v) => (
                    <Option value={v.user_code_id} key={v.user_code_id}>
                      {v.user_code_name}
                    </Option>
                  ))}
                </Select>
                <Input
                  onChange={this.onInputChange}
                  name="user_work"
                  allowClear
                  placeholder="所在公司，没有工作不填"
                  prefix={<ContactsOutlined />}
                />
              </Space>
            </Modal>
            <Popconfirm
              title="确认要删除吗？"
              okText="是"
              cancelText="否"
              onConfirm={this.deletSource.bind(this, text)}
            >
              <DeleteFilled style={{ color: "#7f8c8d" }} />
            </Popconfirm>
          </Space>
        ),
      },
    ];

    return (
      <div>
        <div className="newslist-header">
          <Breadcrumb style={{ margin: "16px 0" }}>
            <Breadcrumb.Item>
              <Link to="/m/index">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>成员管理</Breadcrumb.Item>
            <Breadcrumb.Item>学生列表</Breadcrumb.Item>
          </Breadcrumb>

          <div></div>
        </div>

        <div className="admin-body" style={{ padding: 15, minHeight: 360 }}>
          <Spin tip="Loading..." spinning={this.state.isLoading}>
            <Table
              columns={columns}
              dataSource={this.state.userList}
              // rowSelection={rowSelection}
              pagination={{ pageSize: 8 }}
              // scroll={{ y: 300 }}
            />
          </Spin>
        </div>
      </div>
    );
  }
}

export default NewsList;
